package com.sk.weichat.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.method.PasswordTransformationMethod;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sk.weichat.R;

import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;

import static com.sk.weichat.util.ViewPiexlUtil.dp2px;

public class PasswordInputEditText extends RelativeLayout implements TextWatcher {
    Paint mPaint;
    private int textNum;
    private int radius;
    private int strokeWidth;
    private int strokeColor;
    private int background;
    private int rect_h;
    private EditText editText;
    private int selectIndex;
    private int h;
    private int w;
    private char[] charArray = null;
    int dotRadius;//圆点半径

    public PasswordInputEditText(Context context) {
        this(context, null);
    }

    public PasswordInputEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PasswordInputEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PasswordInputEdittext, defStyleAttr, 0);
        textNum = a.getInteger(R.styleable.PasswordInputEdittext_length, 6);
        radius = a.getDimensionPixelSize(R.styleable.PasswordInputEdittext_corner_radius, 0);
        strokeWidth = a.getDimensionPixelSize(R.styleable.PasswordInputEdittext_stroke_width, 0);
        strokeColor = a.getColor(R.styleable.PasswordInputEdittext_stroke_color, 0xE9E9E9);
        background = a.getColor(R.styleable.PasswordInputEdittext_rect_bg, 0xFFFFFF);
        rect_h = a.getDimensionPixelSize(R.styleable.PasswordInputEdittext_rect_h, 0);

        a.recycle();
        dotRadius = dp2px(context, 6);

        editText = new AppCompatEditText(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            editText.setBackground(null);
        } else {
            editText.setBackgroundColor(Color.WHITE);
        }
        editText.setTextColor(0x00ffffff);
        editText.setTextSize(0.1f);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(textNum)});
        editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); //华为安全键盘

        editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
        editText.setFocusable(true);

        editText.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        editText.addTextChangedListener(this);

        editText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    selectIndex = -1;
                } else {
                    selectIndex = editText.getSelectionStart();
                }
                invalidate();
            }
        });

//        editText.setCustomInsertionActionModeCallback(new ActionMode.Callback() {
//            @Override
//            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//                return false;
//            }
//
//            @Override
//            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
//                return false;
//            }
//
//            @Override
//            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
//                return false;
//            }
//
//            @Override
//            public void onDestroyActionMode(ActionMode mode) {
//
//            }
//        });

        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        addView(editText, layoutParams);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);

    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        drawStroke(canvas, mPaint);

        drawPassword(canvas, mPaint);
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        this.h = h;
        this.w = w;
    }

    private void drawStroke(Canvas canvas, Paint paint) {
        // Log.e("lzs", "strokeWidth:" + strokeWidth + "  strokeColor:" + strokeColor + "  radius:" + radius);
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(strokeColor);

        RectF rectF = new RectF(strokeWidth, strokeWidth, w - strokeWidth, rect_h - strokeWidth);
        canvas.drawRoundRect(rectF, radius, radius, paint);

        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(background);

        rectF = new RectF(strokeWidth * 2, strokeWidth * 2, w - strokeWidth * 2, rect_h - strokeWidth * 2);
        canvas.drawRoundRect(rectF, radius, radius, paint);

        mPaint.setColor(strokeColor);

        float startX = 0;
        float startY = 0;
        float stopX = 0;
        float stopY = 0;
        for (int i = 1; i < textNum; i++) {
            startX = w * 1.0f / textNum * i;
            startY = strokeWidth * 2;
            stopX = startX;
            stopY = w - strokeWidth * 2;
            canvas.drawLine(startX, startY, stopX, stopY, paint);
        }
    }


    private void drawPassword(Canvas canvas, Paint paint) {
        if (charArray == null || charArray.length == 0)
            return;
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.FILL);
        RectF rectF = new RectF();

        for (int i = 0; i < charArray.length; i++) {
            rectF.left = (w * 1.0f / textNum) * (i + 1) - (w * 1.0f / textNum) / 2 - dotRadius;
            rectF.top = h * 1.0f / 2 - dotRadius;
            rectF.right = rectF.left + 2 * dotRadius;
            rectF.bottom = rectF.top + 2 * dotRadius;
            // Log.e("lzs", "left:" + rectF.left + "  top:" + rectF.top + "   rectF.right:" + rectF.right + "  bottom:" + rectF.bottom);
            canvas.drawOval(rectF, paint);
        }
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    private WeakReference<Observer<CharSequence>> mTextWatcher;

    @Override
    public void afterTextChanged(Editable s) {
        Log.e("lzs", "afterTextChanged:" + s.toString());
        if (mTextWatcher != null && mTextWatcher.get() != null) {
            String string = s.toString();
            if (!TextUtils.isEmpty(string)) {
                charArray = string.toCharArray();
                if (charArray.length < textNum) {
                    editText.setSelection(charArray.length);
                }
                selectIndex = charArray.length;
            } else {
                Log.e("lzs", "afterTextChanged:isEmpty");
                charArray = null;
                editText.setSelection(0);
                selectIndex = 0;
            }
            //
            invalidate();
        }
    }

    private int textChangeWacthTime = 1;

    public void setTextWatcher(Observer<CharSequence> mTextWatcher) {
        this.mTextWatcher = new WeakReference<Observer<CharSequence>>(mTextWatcher);
        if (mTextWatcher != null) {
            RxTextView.textChanges(editText)
                    // .throttleLast(textChangeWacthTime, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(mTextWatcher);
        }
    }

    public String getText() {
        if (editText == null) {
            return null;
        }
        return editText.getText().toString();
    }

    public void setText(String text) {
        if (editText == null) {
            return;
        }
        if (TextUtils.isEmpty(text)) {
            charArray = null;
            editText.setSelection(0);
            selectIndex = 0;
            invalidate();
        }
        editText.setText(text);
    }
}
